package other.edan.erp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.api.annotations.*;
import com.rkhd.platform.sdk.data.model.Product;
import com.rkhd.platform.sdk.data.model.User;
import com.rkhd.platform.sdk.model.BatchOperateResult;
import com.rkhd.platform.sdk.model.OperateResult;
import other.edan.erp.utils.ComUtils;
import other.edan.erp.utils.HCXObjectService;
import other.edan.erp.utils.LoggerUtils;

import java.io.IOException;
import java.util.*;

/**
 * ClassName: CrmK3OpenApi
 * Description: openApi接口类
 * date: 2024/6/6
 *
 * @author fwm
 */
@RestApi(baseUrl = "/xobjects/product")
public class CrmK3OpenApi {
    /**
     * 同步产品
     * @return
     */
    @RestMapping(value = "/AddorUpdate", method = RequestMethod.POST)
    public String addorUpdateProduct(@RestBeanParam(name = "data") String data){
        LoggerUtils.info("同步产品参数:"+data);

        try {
          JSONObject productDataJson=JSONObject.parseObject(data);
          LoggerUtils.info("产品JSON:"+productDataJson);
          if(null==productDataJson) {
              return getReturnMsg(201L,false,"接口参数不能为空",null);
          }

          JSONArray productDataArray=productDataJson.getJSONArray("batchData");
          String resultString=productDataCheck(productDataJson,productDataArray);
          if(!(resultString.equals(""))){
              return  resultString;
          }

          Boolean add=productDataJson.getString("type").equals("add");
          resultString=(add)?addProduct(productDataArray):updateProduct(productDataArray);
          LoggerUtils.info("操作结果:"+resultString);
          return resultString;

        } catch (Exception e) {
            String msg="新增/更新产品发生异常，请联系管理员:"+e.getMessage();
            LoggerUtils.error(msg);
            return getReturnMsg(201L,false,msg,null);
        }
    }

    //新增产品
    private String addProduct(JSONArray productDataArray) throws IOException {
        LoggerUtils.info("新增产品数量:"+productDataArray.size());

        JSONArray fCUUnitlDGlobalPick = ComUtils.getGlobalPicks("globalPick37__c");       //单位通用选项集
        JSONArray f105GlobalPick = ComUtils.getGlobalPicks("globalPick53__c");            //产品线通用选项集

        List<Product> productList=new ArrayList<>();
        for(int i=0;i<productDataArray.size();i++){
            JSONObject jsonObject=productDataArray.getJSONObject(i);
            LoggerUtils.info("新增产品:"+jsonObject.toJSONString());

            Product product=new Product();
            product.setEntityType(11010000400001L);                 //业务类型
            product.setParentId(3300190019476122L);                 //产品目录
            product.setProductName(jsonObject.getString("FName"));
            product.setFNumber__c(jsonObject.getString("FNumber"));
            product.setFModel__c(jsonObject.getString("FModel"));

            //TODO
            String FCUUnitlD=jsonObject.getString("FCUUnitID");
            Integer index=ComUtils.getValueByApiKey(fCUUnitlDGlobalPick, FCUUnitlD);
            if(null!=index){
                product.setFCUUnitlD__c(index);
            }

            String f105=jsonObject.getString("F_105");
            index=ComUtils.getValueByApiKey(f105GlobalPick, f105);
            if(null!=index){
                product.setF_105__c(index);
            }

            product.setF_127__c(jsonObject.getString("F_127"));
            product.setF_134__c(jsonObject.getString("F_134"));

            String f_154=jsonObject.getString("F_154");
            product.setF_154__c(f_154);
            product.setF_155__c(jsonObject.getString("F_155"));
            Integer category=Integer.parseInt(f_154.substring(4,5));
            Integer classification=Integer.parseInt(f_154.substring(5,7));

            LoggerUtils.info("f_154="+f_154+",category="+category+",classification="+classification);

            product.setBusinessCategory__c(category);
            product.setProductClassification__c(classification);
            product.setEnableStatus(jsonObject.getInteger("enableStatus"));

            productList.add(product);
        }

        LoggerUtils.info("新增产品数量:"+productList.size());
        BatchOperateResult batchOperateResult = HCXObjectService.insertBatch(productList, true);
        return getReturnMsg(batchOperateResult.getCode(),batchOperateResult.getSuccess(),
                            batchOperateResult.getErrorMessage(),batchOperateResult.getOperateResults());
    }

    //更新产品
    private String updateProduct(JSONArray productDataArray) throws IOException {
        Map<String,JSONObject> fNumberMap=new HashMap<>();          //物料代码，对应的JSON
        StringBuilder condition=new StringBuilder("('1'");
        for(int i=0;i<productDataArray.size();i++){
            JSONObject jsonObject=productDataArray.getJSONObject(i);
            String fNumber=jsonObject.getString("FNumber");
            condition.append(",'").append(fNumber).append("'");

            fNumberMap.put(fNumber,jsonObject);
        }
        condition.append(")");
        String sql="select id,FNumber__c from product where FNumber__c in "+condition;
        List<Product> oldProduct=HCXObjectService.queryAll(sql);
        if(oldProduct.size()==0){
            return  getReturnMsg(201L,false,"没找到需要更新的产品",null);
        }

        JSONArray fCUUnitlDGlobalPick = ComUtils.getGlobalPicks("globalPick37__c");       //单位通用选项集
        JSONArray f105GlobalPick = ComUtils.getGlobalPicks("globalPick53__c");            //产品线通用选项集

        List<Product> newProductList=new ArrayList<>();
        for(Product product:oldProduct){
            JSONObject jsonObject=fNumberMap.get(product.getFNumber__c());
            product.setProductName(jsonObject.getString("FName"));
            product.setFModel__c(jsonObject.getString("FModel"));
            //TODO
            String FCUUnitlD=jsonObject.getString("FCUUnitID");
            Integer index = ComUtils.getValueByApiKey(fCUUnitlDGlobalPick, FCUUnitlD);
            if(null!=index){
                product.setFCUUnitlD__c(index);
            }

            String f105=jsonObject.getString("F_105");
            index=ComUtils.getValueByApiKey(f105GlobalPick, f105);
            if(null!=index){
                product.setF_105__c(index);
            }

            product.setF_127__c(jsonObject.getString("F_127"));
            product.setF_134__c(jsonObject.getString("F_134"));

            String f_154=jsonObject.getString("F_154");
            product.setF_154__c(f_154);
            product.setF_155__c(jsonObject.getString("F_155"));
            Integer category=Integer.parseInt(f_154.substring(4,5));
            Integer classification=Integer.parseInt(f_154.substring(5,7));
            product.setBusinessCategory__c(category);
            product.setProductClassification__c(classification);
            product.setEnableStatus(jsonObject.getInteger("enableStatus"));

            newProductList.add(product);
        }

        LoggerUtils.info("更新产品数量:"+newProductList.size());

        //TODO
        BatchOperateResult batchOperateResult =HCXObjectService.updateBatch(newProductList,true);
        return getReturnMsg(batchOperateResult.getCode(),batchOperateResult.getSuccess(),
                batchOperateResult.getErrorMessage(),batchOperateResult.getOperateResults());
    }

    //校验参数是否正确
    private String productDataCheck(JSONObject productDataJson, JSONArray dataArray){
        String dataCount=productDataJson.getString("count");
        if(null==dataCount){
            return getReturnMsg(201L,false,"数据数量不能为空",null);
        }

        Integer count=Integer.parseInt(dataCount);
        if(count>=40){
            return getReturnMsg(201L,false,"每次新增/更新的数据不能超过40条",null);
        }

        if(dataArray.size()!=count){
            return getReturnMsg(201L,false,"参数中的Count与数据的数量对不上",null);
        }
        return "";
    }

    private String getReturnMsg(Long code,Boolean success, String errorMessage, List<OperateResult> operateResults){
        JSONObject result=new JSONObject();
        result.put("code",code);
        result.put("success",success);
        result.put("errorMessage",errorMessage);
        if(null!=operateResults){
            String or = JSON.toJSONString(operateResults);
            result.put("operateResults",or);
        }
        LoggerUtils.info("返回信息:"+result.toJSONString());
        return result.toJSONString();
    }

    public static void main(String[] args) {
        JSONObject productDataJson=new JSONObject();
        productDataJson.put("type","update");
        productDataJson.put("count",2);

        JSONArray array=new JSONArray();
        for (int i=0;i<2;i++){
            JSONObject product=new JSONObject();
            product.put("FName","FName"+i);
            product.put("FNumber","FNumber"+i);
            product.put("FModel","FModel");
            product.put("FCUUnitID","001");
            product.put("F_105",40004+i);
            product.put("F_127","F_12722222222222");
            product.put("F_134","F_13422222222222222");
            product.put("F_154","20241030607");
            product.put("F_155","F_1553333333333333333");
            product.put("enableStatus",1);
            array.add(product);
        }
        productDataJson.put("batchData",array.toJSONString());

        System.err.println(productDataJson.toJSONString());

        CrmK3OpenApi api=new CrmK3OpenApi();
        api.addorUpdateProduct(productDataJson.toJSONString());
    }
}
